package com.scsj.cloud.authority.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.scsj.cloud.authority.dao.SysMenuMapper;
import com.scsj.cloud.authority.dao.SysUrlMapper;

@Service
public class SysUrlService {

	private final Logger logger=LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private SysUrlMapper urlMapper;
	
	@Autowired
	private SysMenuMapper menuMapper;
	
	@Autowired
	private StringRedisTemplate stringRredisTemplate;
	
	
	/**
	 * Description: 服务启动时加载所有的url接口到redis数据库
	 * 		存储思路: key:角色id+菜单id+接口值    value:接口值
	 * 
	 * @Author caoxiubin
	 * @Create Date: 2019年4月22日 上午11:32:53
	 */
	public void initUrlToRedis() {
		logger.info("开始执行 initUrlToRedis() 方法，将接口数据缓存到 redis 数据库中");
		try {
			//角色对应菜单对应的接口全量信息
			List<Map<String, String>> roleUrlInfo = new ArrayList<Map<String,String>>();
			
			Map<String, String> tempMap = null;
			List<Map<String, Object>> roleMenu = this.menuMapper.selectAllByRole();
			for (Map<String, Object> menuMap : roleMenu) {
				String roleId = menuMap.get("roleId").toString();
				String menuId = menuMap.get("menuId").toString();
				List<Map<String, Object>> menuUrl = this.urlMapper.selectAllByMenuId(Integer.valueOf(menuId));
				for (Map<String, Object> urlMap : menuUrl) {
					String urlPath = String.valueOf(urlMap.get("urlPath"));
					tempMap = Maps.newHashMap();
					tempMap.put("roleId", roleId);
					tempMap.put("menuId", menuId);
					tempMap.put("urlPath", urlPath);
					roleUrlInfo.add(tempMap);
				}
			}
			
			String urlPath = null;
			String urlKey = null;
			for (Map<String, String> map : roleUrlInfo) {
				
				String roleId = map.get("roleId");//角色ID
				String menuId = map.get("menuId");
				urlPath = map.get("urlPath").trim();//接口路径
				urlKey = (roleId + "_" +menuId+ "_" +urlPath).trim();
				
				// 判断key与value是否存在，如果不存在就直接存储
				if (stringRredisTemplate.opsForValue().setIfAbsent(urlKey, urlPath) == false) {
					stringRredisTemplate.opsForValue().set(urlKey, urlPath);
					logger.info("缓存的接口的KEY=====》"+urlKey);
				}
			}
			
			logger.info("接口缓存结束 ！");
			
		} catch (Exception e) {
			logger.error("缓存接口数据 initUrlToRedis() 方法出现异常："+e);
		}
	}
	
}
